
var pageSize = 10;
var i = 2; //设置当前需要获取的页数，全局变量
$(function () {
    function getList(page) {
        i++; //自动增加页码；
        $.ajax({
            type: "get",
            url: "/Home/index/sheetRank/page/" + page + '/limit/' + pageSize,
            success: function (result) {
                $(".loaddiv").hide();
                if (result.code = 200) {
                    var jsonObj = result.data;
                    insertlist(jsonObj);
                    //移除事件重新绑定
                    $('.sheet-collect-count').unbind('click');
                    $('.collect-btn').unbind('click');
                    $('.like-btn').unbind('click');
                    showFavUserList();
                    collectSheet();
                    isLikeSheet();
                    likeSheet();
                }
            },
            beforeSend: function () {
                $(".loaddiv").show();
            },
            error: function () {
                $(".loaddiv").hide();
            }
        });
    }

    /**
     * 生成html数据
     * @param json
     */
    function insertlist(json) {
        var $insertList = $('.sheet-list');
        var rank = $('.sheet-list .list-num').last().text();
        var rank = parseInt(rank);
        var html = '';
        for (var i = 0; i < json.length; i++) {
            rank = rank + 1;
            html += '<li class="sheet-list-info bg-fringe clearfix">';
            html += '<span class="list-num color-red pull-left margin-top-60">' + rank +'</span>';
            html += '<div class="sheet-list-img pull-left margin-top-20 padding-bottom-20 clearfix">';
            html += '<a href="/Home/sheet/index/id/'+ json[i].id + '" target="_blank"><p style="background: transparent url(\'' + json[i].img_url + '\') no-repeat; background-size: 450px;"></p></a>';
            html += '<span class="sheet-count color-red bg-white">' + json[i].img_count + '张</span>';
            html += '</div>';
            html += '<div class="pull-left sheet-list-info-name margin-top-30">';
            html += '<a href="/Home/sheet/index/id/'+ json[i].id + '" target="_blank" class="color-black"><h4 class="margin-0">' + json[i].name + '</h4></a>';
            html += '<div class="margin-top-20">';
            html += '<a href="/Home/user/index/id/' + json[i].creator + '.html" class="display-inlineblock color-black">';
            if (json[i].creator_info.avatar_url) {
                html += '<img class="user-avatar" src="' + json[i].creator_info.avatar_url + '">';
            } else {
                html += '<img class="user-avatar" src="/Public/Home/images/avatar.png">';
            }
            html += '<span>' + json[i]['creator_info']['nickname'] + '</span>';
            html += '</a>';
            html += '</div>';
            html += '</div>';
            html += '<div class="font-size-16 normal-operation-btn color-red" id="normal-operation-btn1">'
            html += '<p class="collect-btn" data-status="' + json[i].collect_status + '" data-id="' + json[i].id + '">收藏</p>';
            html += '<p class="like-btn" data-status="' + json[i].collect_status + '" data-id="' + json[i].id + '"><span>喜欢</span></p>';
            html += '</div>';
            html += '<div class="pull-right sheet-collect-count margin-left-40" id="fav' + rank + '">';
            html += '<p class="">共<span class="color-red">' + json[i].fav_count + '</span>人收藏</p>';
            html += '</div>';
            html += '<ul hidden class="user-list bg-red padding-0" id="user-fav' + rank + '">';
            var fav_user = json[i].fav_user;
            for (var j=0; j < fav_user.length; j++) {
                html += '<li class="user-info margin-top-20 margin-bottom-20 padding-left-18">';
                html += '<a href="/Home/user/index/id="' + fav_user[j].creator + '" class="color-black">';
                html += '<img class="user-avatar" src="' + fav_user[j].avatar_url + '">';
                html += '<span class="user-nickname">' + fav_user[j].nickname + '</span>';
                html += '</a>';
                html += '</li>';
            }
            html += '</ul>';
            html += '</li>';
        }
        $insertList.append(html);

    }

    /**
     * 函数节流，保证只触发一次函数
     * @param method
     * @param context
     */
    function throttle(method, context){
        clearTimeout(method.tId);
        method.tId=setTimeout(function(){
            method.call(method,context);
        }, 500);
    }

    //滚动到底部事件
    function scrollHandler() {
        var winH = $(window).height(); //页面可视区域高度
        var pageH = $(document.body).height(); //页面高度
        var scrollT = $(window).scrollTop(); //滚动条top

        var aa = pageH - winH - scrollT; //body高度-可视区域高度-滚动下移高度
        if (aa < 200) {//0.02是个参数
            //console.log(aa);
            getList(i);
        }
    }
    //定义鼠标滚动事件
    $(window).scroll(function () {
        throttle(scrollHandler, null);
    });
    //==============核心代码 end=============

    /*显示收藏用户列表*/
    function showFavUserList() {
        $('.sheet-collect-count').click(function () {
            id = $(this).attr('id');
            $('#user-' + id).toggle();
        });
    }

    /*收藏曲谱*/
    function collectSheet() {
        $('.collect-btn').click(function () {
            //验证是否登录
            var url = '/Home/login/check';
            var sheet_id = $(this).attr('data-id');
            $.get(url, function (result) {
                if (result.code == 200) {
                    var score_url = '/Home/score/collectSheet/id/'+ sheet_id;
                    layer.open({
                        type: 2,
                        title: '收藏到谱单',
                        area: ['480px', '380px'],
                        content: score_url //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
                    });
                } else if (result.code == 10001) {
                    //登录窗口
                    layer.open({
                        type: 2,
                        title: '',
                        shadeClose: true,
                        area: ['600px', '420px'],
                        content: '/Home/login/index'
                    });
                }
            });
        });
    }

    /*判断用户是否喜欢曲谱*/
    function isLikeSheet() {
        $('.like-btn').each(function () {
            status = $(this).attr('data-status');
            if (status == 1) {
                $(this).addClass('have-like-btn');
                $('.have-like-btn span').hide();
            }
        });
    }


    /*喜欢曲谱*/
    function likeSheet() {
        $('.like-btn').click(function () {
            var now_status = $(this).attr('data-status');
            var id = $(this).attr('data-id');
            var status = 1;
            var url = '/Home/sheet/favSheet';
            var _this = $(this);
            if (now_status == 1) {
                status = 0;
                var data = {"status":status,"sheet_id":id};
                $.post(url, data, function (result) {
                    console.log(result.code);
                    if (result.code == 200) {
                        _this.attr('data-status', 0);
                        _this.removeClass('have-like-btn');
                        _this.find("span").show();
                    } else if (result.code == 10001) {
                        layer.msg(result.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                });
            } else {
                var data = {"status":status,"sheet_id":id};
                $.post(url, data, function (result) {
                    console.log(result.code);
                    if (result.code == 200) {
                        _this.attr('data-status', 1);
                        _this.addClass('have-like-btn');
                        _this.find("span").hide();
                    } else if (result.code == 10001) {
                        //登录窗口
                        layer.open({
                            type: 2,
                            title: '',
                            area: ['600px', '420px'],
                            content: '/Home/login/index'
                        });
                    }
                });
            }
        });
    }
});